package com.bp.scoringgun.service.impl;

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
@Component
public class GitHubAPIServiceImpl {

    @Value("${scoring-gun.token}")
    private String token;
    // 第一个函数：获取组织的 location 字段
    public String getLocation(String orgUrl) {
        try {
            // 构造 URL 对象
            URL url = new URL(orgUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            //conn.setRequestProperty("Accept", "application/vnd.github.v3+json");
            conn.setRequestProperty("Authorization", "token " + token);
            conn.setRequestProperty("User-Agent", "Scoring-gun");
            // 获取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            // 解析 JSON 响应
            JSONObject jsonResponse = new JSONObject(response.toString());
            System.out.println("response: " + jsonResponse.toString());
            return jsonResponse.getString("location");  // 返回 location 字段
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }finally {
            // 休眠 0.72 秒，避免超过速率限制
            try {
                Thread.sleep(720); // 暂停 0.72秒
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
        }
    }

    // 第二个函数：获取用户的 repos_url 字段
    public String getUserReposUrl(String userUrl) {
        try {
            // 构造 URL 对象
            URL url = new URL(userUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "token " + token);
            conn.setRequestProperty("User-Agent", "Scoring-gun");

            // 获取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析 JSON 响应
            JSONObject jsonResponse = new JSONObject(response.toString());
            return jsonResponse.getString("repos_url");  // 返回 repos_url 字段
        } catch (Exception e) {
            return "";
        }finally {
            // 休眠 0.72 秒，避免超过速率限制
            try {
                Thread.sleep(720); // 暂停 0.72 秒
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
        }
    }

    // 第三个函数：获取仓库语言的集合
    public String getRepoLanguages(String reposUrl) {
        try {
            // 构造 URL 对象
            URL url = new URL(reposUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Authorization", "token " + token);
            conn.setRequestProperty("User-Agent", "Scoring-gun");

            // 获取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析 JSON 响应
            JSONArray jsonResponse = new JSONArray(response.toString());
            Set<String> languagesSet = new HashSet<>();  // 使用 HashSet 来去重

            // 遍历仓库列表，提取 language 字段
            for (int i = 0; i < jsonResponse.length(); i++) {
                JSONObject repo = jsonResponse.getJSONObject(i);
                if (repo.has("language") && repo.getString("language") != null) {
                    languagesSet.add(repo.getString("language"));  // 添加到 Set 中，自动去重
                }
            }

            // 拼接不重复的语言
            StringBuilder languages = new StringBuilder();
            for (String language : languagesSet) {
                if (languages.length() > 0) {
                    languages.append(" , ");  // 如果不是第一个元素，添加逗号和空格
                }
                languages.append(language);
            }

            // 如果没有任何语言，则返回空字符串，否则返回拼接的语言字符串
            return languages.length() > 0 ? "[ " + languages + " ]" : "[]";
        } catch (Exception e) {
            return "[]";  // 出错时返回空集合的字符串 "[]"
        }finally {
            // 休眠 0.72 秒，避免超过速率限制
            try {
                Thread.sleep(720); // 暂停0.72 秒
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
        }
    }
}
